import { Form, Modal, Row, Col, Input, Select, InputNumber } from 'antd';
import { useEffect, useState } from 'react';
import { connect } from 'umi';
import { normFile, uuid } from '@/utils/upload';
import AliyunOSSUploadFile from '@/components/AliyunOSSUploadFile/App';

const DataForm = (props) => {
  const { dispatch, submitting } = props;
  const { dataForm, setDataForm, tablePayload, setTablePayload } = props.data;
  const [form] = Form.useForm();
  const [img, setImg] = useState([]);
  const [icon, setIcon] = useState([]);

  /* 初始化表单数据 */
  useEffect(() => {
    if (!dataForm || !dataForm.data) {
      form.setFieldsValue({ status: 1, orderby: 0 });
    }
    if (dataForm && dataForm.data) {
      let { data } = dataForm;

      let img_ = [];
      if (dataForm.data.img) {
        img_ = [{ uuid: uuid(), name: dataForm.data.img.split('/').pop(), status: 'done', url: dataForm.data.img }];
      }
      setImg(img_);

      let icon_ = [];
      if (dataForm.data.icon) {
        icon_ = [{ uuid: uuid(), name: dataForm.data.icon.split('/').pop(), status: 'done', url: dataForm.data.icon }];
      }
      setIcon(icon_);

      form.setFieldsValue({
        ...data,
        img: img_,
        icon: icon_,
      });
    }
    if (dataForm && dataForm.parent) {
      form.setFieldsValue({ pid: dataForm.parent.id });
    }
  }, [dataForm, form]);

  /* 确定操作 */
  function onOk() {
    form.validateFields().then(values => {
      if (submitting) {
        return;
      }
      let keys = Object.keys(values);
      keys.forEach(d => {
        values[d] = values[d] === null ? undefined : values[d];
      });

      if (values.img && (values.img.length > 0)) {
        values.img = values.img.filter(d => d.status === 'done').pop().url;
      } else {
        values.img = '';
      }

      if (values.icon && (values.icon.length > 0)) {
        values.icon = values.icon.filter(d => d.status === 'done').pop().url;
      } else {
        values.icon = '';
      }

      dispatch({
        type: values.id ? 'PMallGoodsCates/edit' : 'PMallGoodsCates/add',
        payload: values,
        callback: () => {
          onCancel();
          setTablePayload({ ...tablePayload });
          dispatch({ type: 'MallCommon/fetchGoodsCateList', payload: {} });
        },
      });
    });
  }

  /* 取消操作 */
  function onCancel() {
    setDataForm(undefined);
    form.resetFields();
    setImg([]);
    setIcon([]);
  }

  return (
    <Modal
      confirmLoading={submitting}
      title={dataForm ? dataForm.title : ''}
      open={dataForm ? dataForm.visible : false}
      onOk={onOk}
      onCancel={onCancel}
      forceRender={true}
      width={600}
      bodyStyle={{ paddingTop: 24 }}
    >
      <Form layout="horizontal" labelCol={{ span: 4 }} form={form}>
        {dataForm && dataForm.data && (
          <Form.Item name="id" hidden={true}>
            <Input />
          </Form.Item>
        )}
        {dataForm && dataForm.parent && (
          <Form.Item name="pid" hidden={true}>
            <Input />
          </Form.Item>
        )}
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name="name" label="分类名称"
              rules={[
                { required: true, message: '分类名称不能为空' },
              ]}>
              <Input placeholder="请输入分类名称" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name="status" label="当前状态"
              rules={[
                { required: true, message: '当前状态不能为空' },
              ]}
            >
              <Select placeholder="请选择当前状态">
                <Select.Option value={1}>正常</Select.Option>
                <Select.Option value={0}>停用</Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name={'icon'} label="分类图标"
              rules={[
                { required: false, message: '分类图标不能为空' },
              ]}
              valuePropName="fileList" getValueFromEvent={normFile}>
              <AliyunOSSUploadFile
                data={{ images: icon, setImages: setIcon, size: 10, len: 1, accept: 'image/*' }} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name={'img'} label="分类图片"
              rules={[
                { required: false, message: '分类图片不能为空' },
              ]}
              valuePropName="fileList" getValueFromEvent={normFile}>
              <AliyunOSSUploadFile
                data={{ images: img, setImages: setImg, size: 10, len: 1, accept: 'image/*' }} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name="link" label="跳转链接"
              rules={[
                { required: false, message: '跳转链接不能为空' },
              ]}>
              <Input placeholder="请输入跳转链接" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name="orderby" label="排序属性"
              rules={[
                { required: true, message: '排序属性不能为空' },
              ]}>
              <InputNumber style={{ width: '100%' }} placeholder="请输入排序属性" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name="remark" label="备注信息"
              rules={[
                { required: false, message: '备注信息不能为空' },
              ]}
            >
              <Input.TextArea rows={3} placeholder="请输入备注信息" />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};


export default connect(({ loading }) => {
  return {
    submitting: loading.effects['PMallGoodsCates/add'] || loading.effects['PMallGoodsCates/edit'],
  };
})(DataForm);

